﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

namespace Legend.Threading
{
    /// <summary>
    /// An adapter class providing the ITimer-interface 
    /// for the System.Timers.Timer-class.
    /// </summary>
    public class TimerAdapter
        : ITimer
    {
        private Timer timer;

        /// <summary>
        /// Creates a new instance.
        /// </summary>
        /// <param name="timer">The timer to adapt.</param>
        public TimerAdapter(Timer timer)
        {
            Require.ThatArgument(timer).Named("timer").IsNotNull();
        
            this.timer = timer;
            this.timer.Elapsed += this.timer_Elapsed;
        }

        /// <summary>
        /// Creates a new instance.
        /// </summary>
        /// <param name="interval">The interval at which the timer
        /// should raise the Elapsed-event.</param>
        public TimerAdapter(TimeSpan interval)
            : this(new Timer(interval.TotalMilliseconds))
        { 
            
        }

        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (this.Elapsed != null)
            {
                this.Elapsed(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Occurs a given interval.
        /// </summary>
        public event EventHandler Elapsed;

        /// <summary>
        /// Starts raising the Elapsed-event.
        /// </summary>
        public void Start()
        {
            this.timer.Start();
        }

        /// <summary>
        /// Stop raising the Elapsed-event.
        /// </summary>
        public void Stop()
        {
            this.timer.Stop();
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.timer.Dispose();
        }

        /// <summary>
        /// A factory delegate that creates TimerAdapter-instances.
        /// </summary>
        public static readonly TimerFactory Factory = x => new TimerAdapter(x);
    }
}